package com.gxuwz.entity;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import javax.persistence.*;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 用户实体
 * @author 小胡  
 * @date 2017年5月28日
 */
@Entity
@Table(name = "sys_user")
public class SysUser extends BaseEntity implements UserDetails{

	private static final long serialVersionUID = 103889943178214590L;

	@Column(name = "user_name", unique = true, nullable = false)
	private String userName; // 用户名
	@Column(name = "user_password")
	private String userPassword; // 密码
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
	private Set<SysRole> user_role; // 所属角色
	@Column(name = "telephone")
	private String telephone; // 电话
	@Column(name = "user_create_date")
	private String createDate; // 创建日期
	@ManyToMany(fetch = FetchType.EAGER)
	@JoinTable(name = "sys_user_lab", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "lab_id"))
	private Set<SysLaboratory> user_lab;

	public SysUser() {

	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getUserPassword() {
		return userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public Set<SysRole> getUser_role() {
		return user_role;
	}

	public void setUser_role(Set<SysRole> user_role) {
		this.user_role = user_role;
	}

	public String getTelephone() {
		return telephone;
	}

	public void setTelephone(String telephone) {
		this.telephone = telephone;
	}

	public String getCreateDate() {
		return createDate;
	}

	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}

	public Set<SysLaboratory> getUser_lab() {
		return user_lab;
	}

	public void setUser_lab(Set<SysLaboratory> user_lab) {
		this.user_lab = user_lab;
	}
	
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		Set<GrantedAuthority> auths = new HashSet<>();
        Set<SysRole> roles = this.getUser_role();
		// 默认所有的用户有"USER"的权利
        auths.add(new SimpleGrantedAuthority("ROLE_USER"));
        for (SysRole role : roles) {
            auths.add(new SimpleGrantedAuthority(role.getRoleName()));
        }
        return auths;
	}

	@Override
	public String getPassword() {
		return this.userPassword;
	}

	@Override
	public String getUsername() {
		return this.userName;
	}

	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

}
